/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.common.service;

import org.springframework.transaction.annotation.Transactional;

import cn.net.ecode.common.persistence.CrudDao;
import cn.net.ecode.common.persistence.DataEntity;

/**
 * Service基类
 * @author ThinkGem
 * @version 2014-8-19
 */
@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<?>> extends QueryService<D, T> {
	
	/**
	 * 插入数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void insert(T entity) {
		entity.setIsNewRecord(true);
		save(entity);
	}
	
	/**
	 * 更新数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void update(T entity) {
		entity.setIsNewRecord(false);
		save(entity);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void save(T entity) {
		if (entity.getIsNewRecord()){
			entity.preInsert();
			dao.insert(entity);
		}else{
			entity.preUpdate();
			dao.update(entity);
		}
	}
	
	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void delete(T entity) {
		entity.preUpdate();
		dao.delete(entity);
	}

}
